﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Artefact.Animation;

using WebFlipScreenSaver.Model;

namespace WebFlipScreenSaver.View
{
	/// <summary>
	/// Interaction logic for ScreenSaverView.xaml
	/// </summary>
	public partial class ScreenSaverView : Window
	{

		private ScreenSaverViewModel _screenSaverViewModel = new ScreenSaverViewModel();
		DispatcherTimer _pageChangeTimer = new DispatcherTimer();
		DispatcherTimer _secondsTimer = new DispatcherTimer();
		private SettingsViewModel _settings;

		private WebPageViewModel _currentPageViewModel;
		public ScreenSaverView()
		{
			InitializeComponent();
			DataContext = _screenSaverViewModel;
			_settings = FlipperSettings.LoadSettings();

			if (_settings.WebsiteConfigurations != null)
			{
				foreach (var config in _settings.WebsiteConfigurations.OrderByDescending(x => x.WebSiteUrl))
				{
					_currentPageViewModel = new WebPageViewModel { WebConfig = config };
					var webPageView = _screenSaverViewModel.CurrentWebPage = new WebPageView() { DataContext = _currentPageViewModel };
					_screenSaverViewModel.CurrentWebPage.Opacity = 1;
					_screenSaverViewModel.WebPages.Add(webPageView);
					//BrowserGrid.Children.Add(webPageView);
				}
			}
			_activePane = Pane1;
			_inactivePane = Pane2;
			_activePane.Content = _screenSaverViewModel.CurrentWebPage;



            
			//.Content

			_screenSaverViewModel.CurrentWebPage.Opacity = 1;
			//TransitionBox.Content = _currentPageView;

			_screenSaverViewModel.NextWebPage = GetNextPage();
			_pageChangeTimer.Interval = new TimeSpan(0, 0, 0, _currentPageViewModel.WebConfig.DisplayTime);
			_pageChangeTimer.Tick += new EventHandler(_timer_Tick);
			_pageChangeTimer.Start();

			_secondsTimer.Interval = new TimeSpan(0,0,0,1);
			_secondsTimer.Tick += new EventHandler(_secondsTimer_Tick);
			_secondsTimer.Start();


			Loaded += new RoutedEventHandler(ScreenSaverView_Loaded);
			//OverlayControls.IsOpen = true;

            if (_settings.WebsiteConfigurations.Count == 0) return;
            var content = GetNextPage();
            if (content != _activePane.Content)
            {
                _inactivePane.Content = content;
            }

			PreviewKeyUp += new KeyEventHandler(ScreenSaverView_PreviewKeyUp);
        }

		void ScreenSaverView_PreviewKeyUp(object sender, KeyEventArgs e)
		{
			if(e.Key == Key.Right)
			{
				_pageChangeTimer.Stop();
				MoveNextPage();
			}
			else if(e.Key == Key.Left)
			{
				_pageChangeTimer.Stop();
				MovePreviousPage();
				
			}
		}


		void _secondsTimer_Tick(object sender, EventArgs e)
		{
			_currentPageViewModel.SecondsUntilPageChange =
				(int)Math.Ceiling((_currentPageViewModel.DisplayedStartTime.AddSeconds(_currentPageViewModel.WebConfig.DisplayTime) - DateTime.Now).TotalSeconds);
			_currentPageViewModel.SecondsUntilRefresh = 
			(int)Math.Ceiling((_currentPageViewModel.LastRefreshTime.AddSeconds(_currentPageViewModel.WebConfig.RefreshIntervalSecs) - DateTime.Now).TotalSeconds);
		}

		void ScreenSaverView_Loaded(object sender, RoutedEventArgs e)
		{
		
		}

		void _timer_Tick(object sender, EventArgs e)
		{
			_pageChangeTimer.Stop();
            if (_screenSaverViewModel.WebPages.Count > 1)
                TransitionNext(TransitionDirection.Right);
            else
                _pageChangeTimer.Start();
		}

		private WebPageView GetNextPage()
		{
            var page = _screenSaverViewModel.NextWebPage ?? _screenSaverViewModel.CurrentWebPage;
            if ( page == null) return null;
			var nextPageIndex = _screenSaverViewModel.WebPages.IndexOf(page) + 1;
			if (nextPageIndex > _screenSaverViewModel.WebPages.Count - 1)
			{
				nextPageIndex = 0;
			}
			return _screenSaverViewModel.WebPages[nextPageIndex];
		}

		private WebPageView GetPreviousPage()
		{
			var page = _screenSaverViewModel.NextWebPage ?? _screenSaverViewModel.CurrentWebPage;
			if (page == null) return null;
			var previousPageIndex = _screenSaverViewModel.WebPages.IndexOf(page) - 1;
			if (previousPageIndex < 0)
			{
				previousPageIndex = _screenSaverViewModel.WebPages.Count - 1;
			}
			return _screenSaverViewModel.WebPages[previousPageIndex];
		}

		private ContentControl _activePane, _inactivePane;

		private void TransitionNext(TransitionDirection fromDirection)
		{

			//MoveNextPage();
			MovePreviousPage();
		}

		void EaseNextComplete(EaseObject easeObject, double percent)
		{
			ChangeToNextPage();

			_pageChangeTimer.Interval = new TimeSpan(0, 0, 0, _currentPageViewModel.WebConfig.DisplayTime);
			_pageChangeTimer.Start();
		}

		void MoveNextPage()
		{
			_inactivePane.SetValue(Canvas.LeftProperty, _activePane.ActualWidth);
			ArtefactAnimator.AddEase(_inactivePane, Canvas.LeftProperty, 0, .7, AnimationTransitions.CubicEaseOut, 0);
			var ease = ArtefactAnimator.AddEase(_activePane, Canvas.LeftProperty, -_activePane.ActualWidth, .7, AnimationTransitions.CubicEaseOut, 0);
			ease.Complete += new EaseObjectHandler(EaseNextComplete);
		}

		void ChangeToNextPage()
		{
			var temp = _activePane;
			_activePane = _inactivePane;
			_inactivePane = temp;
			
			_screenSaverViewModel.CurrentWebPage = _screenSaverViewModel.NextWebPage;
			_screenSaverViewModel.NextWebPage = GetNextPage();

			var parent = _screenSaverViewModel.NextWebPage.Parent;
			if (parent is ContentControl)
			{
				(parent as ContentControl).Content = null;
			}
			_inactivePane.Content = _screenSaverViewModel.NextWebPage;

			_currentPageViewModel = _screenSaverViewModel.CurrentWebPage.DataContext as WebPageViewModel;
			_currentPageViewModel.DisplayedStartTime = DateTime.Now;


		}

		void EasePreviousComplete(EaseObject easeObject, double percent)
		{
			ChangeToPreviousPage();

			_pageChangeTimer.Interval = new TimeSpan(0, 0, 0, _currentPageViewModel.WebConfig.DisplayTime);
			_pageChangeTimer.Start();
		}

		void MovePreviousPage()
		{
			_inactivePane.SetValue(Canvas.LeftProperty, -_inactivePane.Width);
			ArtefactAnimator.AddEase(_inactivePane, Canvas.LeftProperty, 0, .7, AnimationTransitions.CubicEaseOut, 0);
			var ease = ArtefactAnimator.AddEase(_activePane, Canvas.LeftProperty, _activePane.ActualWidth, .7, AnimationTransitions.CubicEaseOut, 0);
			ease.Complete += new EaseObjectHandler(EasePreviousComplete);
		}

		void ChangeToPreviousPage()
		{
			var temp = _activePane;
			_activePane = _inactivePane;
			_inactivePane = temp;
			
			_screenSaverViewModel.CurrentWebPage = _screenSaverViewModel.NextWebPage;
			_screenSaverViewModel.NextWebPage = GetPreviousPage();

			var parent = _screenSaverViewModel.NextWebPage.Parent;
			if (parent is ContentControl)
			{
				(parent as ContentControl).Content = null;
			}
			_inactivePane.Content = _screenSaverViewModel.NextWebPage;

			_currentPageViewModel = _screenSaverViewModel.CurrentWebPage.DataContext as WebPageViewModel;
			_currentPageViewModel.DisplayedStartTime = DateTime.Now;
		}

		void ScreenSaverView_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
		{
			_screenSaverViewModel.CurrentWebPage.browser.WebBrowser().LoadCompleted -= ScreenSaverView_LoadCompleted;
			if (_currentPageViewModel.WebConfig.RequiresAuth)
			{
				
				_screenSaverViewModel.CurrentWebPage.LoginWebPage(_currentPageViewModel.WebConfig, _screenSaverViewModel.CurrentWebPage);
			}

			
		}



		private void ShowSettingsButton_Click(object sender, RoutedEventArgs e)
		{
			var settingsView = new Settings(_settings);
			settingsView.Owner = this;
			settingsView.Show();
		}


	}
}



public enum TransitionDirection
{
	Right,
	Left,
	Top,
	Bottom
}